﻿using SharpDX.Direct3D11;
using System.Windows.Forms;
using SharpDX;
using SharpDX.D3DCompiler;
using SharpDX.DXGI;
using SharpDX.Windows;
using Device = SharpDX.Direct3D11.Device;
using System.Runtime.InteropServices;

namespace Engine
{
    public class MeshContainer : ResourceContainer, System.IDisposable
    {
        public Buffer Indices;
        public Buffer Vertexs;

        public VertexBufferBinding binding;

        public int VertexsCount, BytesPerVertex, FaceCount;

        public Vector3 LocalAABBMax = new Vector3();
        public Vector3 LocalAABBMin = new Vector3();

        public MeshContainer() { }

        public MeshContainer(Engine.Serialize.Mesh M)
        {
            if (M != null)
            {
                LocalAABBMax = M.AABBMax;
                LocalAABBMin = M.AABBMin;

                VertexsCount = M.VertexCount;
                FaceCount = M.FaceCount;
                BytesPerVertex = M.VertexData.Length / VertexsCount;

                using (var vertices = new DataStream(BytesPerVertex * VertexsCount, true, true))
                {
                    vertices.WriteRange<byte>(M.VertexData, 0, M.VertexData.Length);
                    vertices.Position = 0;
                    Vertexs = new Buffer(ModelViewer.Program.device, vertices, BytesPerVertex * VertexsCount, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
                    binding = new VertexBufferBinding(Vertexs, BytesPerVertex, 0);
                }

                using (var indices = new DataStream(4 * FaceCount * 3, true, true))
                {
                    indices.WriteRange<byte>(M.IndexData, 0, M.IndexData.Length);
                    indices.Position = 0;
                    Indices = new Buffer(ModelViewer.Program.device, indices, 4 * FaceCount * 3, ResourceUsage.Default, BindFlags.IndexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
                }
            }
        }

        #region IDisposable
        //Ok
        ~MeshContainer()
        {
            Dispose();
        }

        public void Dispose()
        {
            if (Vertexs != null) Vertexs.Dispose();
            if (Indices != null) Indices.Dispose();
        }
        #endregion

    }
}
